#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from flask import Flask, request, jsonify
import os

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/cmd', methods=['POST'])
def execute_cmd():
    data = request.get_json()
    if not data or 'command' not in data:
        return jsonify({'error': '缺少 command 参数'}), 400
    
    command = data['command']
    try:
        result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True, universal_newlines=True)
        return jsonify({
            'stdout': result.stdout.replace('\r\n', '\n'),
            'stderr': result.stderr.replace('\r\n', '\n'),
            'returncode': result.returncode
        })
    except subprocess.CalledProcessError as e:
        result = subprocess.run(command, shell=True, check=False, text=True, capture_output=True, universal_newlines=True)
        return jsonify({
            'stdout': result.stdout.replace('\r\n', '\n'),
            'stderr': result.stderr.replace('\r\n', '\n'),
            'returncode': result.returncode
        }), 500

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '未找到文件'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '未选择文件'}), 400
    if file:
        filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filename)
        return jsonify({'message': '文件上传成功', 'filename': file.filename}), 200

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')